#include <bits/stdc++.h>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    vector<vector<int>> levelOrder(TreeNode *root)
    {
        vector<vector<int>> res;
        queue<TreeNode *> que;
        if (root != nullptr)
        {
            que.push(root);
        }
        while (!que.empty())
        {
            int length = que.size();
            vector<int> vec;
            for (int i = 0; i < length; i++)
            {
                TreeNode *node = que.front();
                que.pop();
                vec.push_back(node->val);
                if (node->left)
                {
                    que.push(node->left);
                }
                if (node->right)
                {
                    que.push(node->right);
                }
            }
            res.push_back(vec);
        }
        return res;
    }

    vector<int> rightSideView(TreeNode *root)
    {
        vector<int> res;
        vector<vector<int>> order_vec = levelOrder(root);
        for (auto vec : order_vec)
        {
            res.push_back(*vec.rbegin());
        }
        return res;
    }

    // void order(TreeNode *node, vector<vector<int>> &vec, int deep)
    // {
    //     if (node == nullptr)
    //     {
    //         return;
    //     }
    //     if (vec.size() == (size_t)deep)
    //     {
    //         vec.push_back(vector<int>());
    //     }
    //     vec[deep].push_back(node->val);
    //     order(node->left, vec, deep + 1);
    //     order(node->right, vec, deep + 1);
    // }

    // vector<vector<int>> levelOrder(TreeNode *root)
    // {
    //     vector<vector<int>> res;
    //     int deep = 0;
    //     order(root, res, deep);
    //     return res;
    // }
};

int main()
{
    TreeNode *root = new TreeNode(3);
    TreeNode *node1 = new TreeNode(9);
    TreeNode *node2 = new TreeNode(20);
    TreeNode *node3 = new TreeNode(15);
    TreeNode *node4 = new TreeNode(7);

    root->left = node1;
    root->right = node2;
    node2->left = node3;
    node2->right = node4;

    Solution sol;
    vector<int> res = sol.rightSideView(root);
    for (auto num : res)
    {
        cout << num << " ";
    }
    cout << endl;
    return 0;
}